package wechat

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type TemplateOrderNoticeDataValue struct {
	Value string `json:"value"`
}

type TemplateOrderNoticeData struct {
	First         TemplateOrderNoticeDataValue `json:"first"`
	TradeDateTime TemplateOrderNoticeDataValue `json:"tradeDateTime"` // 时间
	OrderType     TemplateOrderNoticeDataValue `json:"orderType"`     // 订单类型
	CustomerInfo  TemplateOrderNoticeDataValue `json:"customerInfo"`  // 客户信息
	OrderItemName TemplateOrderNoticeDataValue `json:"orderItemName"`
	OrderItemData TemplateOrderNoticeDataValue `json:"orderItemData"`
	Remark        TemplateOrderNoticeDataValue `json:"remark"`
}

type TemplateOrderNotice struct {
	Touser     string                  `json:"touser"`
	TemplateId string                  `json:"template_id"`
	Url        string                  `json:"url"`
	Data       TemplateOrderNoticeData `json:"data"`
}

type TemplateOrderNoticeRes struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	Msgid   string `json:"msgid"`
}

// 发送订单通知
func SendOrderNotice(openid, first, remark, url, k1, k2, k3, k4, k5 string) {
	t := TemplateOrderNotice{
		Touser:     openid,
		TemplateId: beego.AppConfig.String("ordernoticeid"),
		Url:        url,
		Data: TemplateOrderNoticeData{
			First:         TemplateOrderNoticeDataValue{Value: first},
			TradeDateTime: TemplateOrderNoticeDataValue{Value: k1},
			OrderType:     TemplateOrderNoticeDataValue{Value: k2},
			CustomerInfo:  TemplateOrderNoticeDataValue{Value: k3},
			OrderItemName: TemplateOrderNoticeDataValue{Value: k4},
			OrderItemData: TemplateOrderNoticeDataValue{Value: k5},
			Remark:        TemplateOrderNoticeDataValue{Value: remark},
		},
	}
	content, err := json.Marshal(t)
	if err != nil {
		logs.Error("can not marshal safe notice struct:", err)
		return
	}
	ret := SendTemplateMsg("xianzhi", string(content))
	res := TemplateOrderNoticeRes{}
	err = json.Unmarshal([]byte(ret), &res)
	if err != nil {
		logs.Error("can not unmarshal send safe notice response:", err)
		return
	}
	if res.Errcode != 0 {
		logs.Error("send safe notice fail:", res.Errmsg)
		return
	}
}
